#include "../include/ink_module_mgr.h"
#include "../include/ink_module_i.h"
#include "../include/ink_hash.h"

namespace ink
{

module_i* module_mgr::get_module_by_id( uint32_t id ) {
    module_container_t::iterator iter = modules_.find(id);
    return iter == modules_.end() ? 0 : iter->second;
}

void module_mgr::add_module( module_i* module ) {
    module_container_t::iterator iter = modules_.find(module->id());
    if (iter != modules_.end()) {
        return ; // already exist, does nothing
    }
    modules_[module->id()] = module;
}

void module_mgr::register_creator( const std::string& name, module_creator* creator )
{
    uint32_t hash_value = string_hash(name.c_str());
    if (module_creators_.find(hash_value) == module_creators_.end()) {
        module_creators_[hash_value] = creator;
    }
}

module_i* module_mgr::create_module( const std::string& name )
{
    uint32_t hash_value = string_hash(name.c_str());
    if (module_creators_.find(hash_value) != module_creators_.end()) {
        module_i* mod = module_creators_[hash_value]->create();
        mod->set_id(hash_value);
        add_module(mod);
        return mod;
    }

    return 0;
}
} // namespace ink
